package jp.co.redfox.archclub.poker;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YesNoQuery {
    private Set<YesNoListener> listenerSet = new CopyOnWriteArraySet<YesNoListener>();
    
    private static final Pattern yesPattern = Pattern.compile("[yY]|([yY][eE][sS])");
    private static final Pattern noPattern = Pattern.compile("[nN]|([nN][oO])");
    private String answerType = "y/n";
    
    public void addListener(YesNoListener listener) {
        listenerSet.add(listener);
    }

    public void ask(String question) {
        System.out.println(question + this.answerType);
        Scanner sc = new Scanner(System.in);
        String res = sc.nextLine();
        while (true) {
            if (yesPattern.matcher(res).matches()) {
                notifyYesListeners();
                break;
            }
            else if (noPattern.matcher(res).matches()) {
                notifyNoListeners();
                break;
            }
            else {
                System.out.println(this.answerType + "の形式で入力して下さい。");
                System.out.println(question + this.answerType);
                res = sc.nextLine();
            }
        }
    }

    private void notifyNoListeners() {
        for (YesNoListener listener : listenerSet)
            listener.onNo();
    }

    private void notifyYesListeners() {
        for (YesNoListener listener : listenerSet)
            listener.onYes();
    }
}
